package net.sareweb.acab.entity.manager;

import java.util.Date;
import java.util.GregorianCalendar;
import java.util.List;

import net.sareweb.acab.entity.Comment;
import net.sareweb.acab.entity.Seat;
import net.sareweb.acab.entity.Travel;

import org.jboss.seam.ScopeType;
import org.jboss.seam.annotations.Logger;
import org.jboss.seam.annotations.Name;
import org.jboss.seam.annotations.Scope;
import org.jboss.seam.log.Log;

@Name("travelManager")
@Scope(ScopeType.CONVERSATION)
public class TravelManager extends CommonManager<Travel> {
	@Logger
	private Log log;
	
	public int getFreeSeatAmount(Travel t){
		List<Seat> l = t.getSeats();
		if(l == null) return 0;
		int counter = 0;
		for (int i = 0; i < l.size(); i++) {
			Seat s = l.get(i);
			if(s.getState().equals(SeatManager.SEAT_STATE_FREE))counter++ ;
		}		
		return counter;
	}
	
	
	public List<Travel> getLastNTravels(int n){
		List<Travel> t =  entityManager.createQuery(_GET_LAST_N_TRAVELS).setMaxResults(n).getResultList();
		log.debug("Last {0} travels. Max {1}", t.size(), n);
		return t;
	}
	
	public List<Travel> getTravelsSoon(){
		//TODO: mejorar  este algoritmo
		Date fromDate = new Date();
		GregorianCalendar cal = new GregorianCalendar();
		cal.setTime(fromDate);
		cal.add(GregorianCalendar.HOUR, 48);
		Date toDate = cal.getTime();
		
		List<Travel> t =  entityManager.createQuery(_GET_TRAVELS_FROM_NOW).setParameter("fromDate", fromDate).setParameter("toDate", toDate).getResultList();
		log.debug("{0} travel Soon.", t.size());
		return t;
	}
	
	
	
	
	
	private String _GET_LAST_N_TRAVELS ="from Travel order by createDate desc";
	private String _GET_TRAVELS_FROM_NOW ="from Travel order where (singleDay=true and beginDate between :fromDate and :toDate)";
	
}
